/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.spring.web.bind;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.vacoor.nothing.common.util.StringUtils;
import org.vacoor.nothing.web.domain.Sort;

/**
 * jQuery easy-ui / jqGrid 风格排序参数解析器 (吐槽下, easy-ui 扩展性不好, 还不开源..)
 * sort=name,url&order=asc,desc
 * <p/>
 * {@link org.vacoor.nothing.web.domain.Sort}
 *
 * @author vacoor
 */
public class SortHandlerMethodArgumentResolver2 extends SortHandlerMethodArgumentResolver {
    private static final String DEFAULT_PROPERTIES_PARAMETER_NAME = "sort";
    private static final String DEFAULT_DIRECTION_PARAMETER_NAME = "order";
    private static final String DEFAULT_VALUE_DELIMITER = ",";

    private String propertiesParameterName = DEFAULT_PROPERTIES_PARAMETER_NAME;
    private String ordersParameterName = DEFAULT_DIRECTION_PARAMETER_NAME;
    private String valueDelimiter = DEFAULT_VALUE_DELIMITER;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return Sort.class.equals(parameter.getParameterType());
    }

    @Override
    public Sort resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String propertiesStr = webRequest.getParameter(getParameterName(propertiesParameterName, parameter));
        String directionsStr = webRequest.getParameter(getParameterName(ordersParameterName, parameter));

        String[] properties = propertiesStr != null ? propertiesStr.split(valueDelimiter) : new String[0];
        String[] directions = directionsStr != null ? directionsStr.split(valueDelimiter) : new String[0];

        Sort sort = Sort.create();
        for (int i = 0; i < properties.length; i++) {
            String prop = properties[i];
            if (!StringUtils.hasText(prop)) continue;

            Sort.Direction dir = i < directions.length ? Sort.Direction.forName(directions[i]) : null;
            dir = dir != null ? dir : getFallbackDirection();
            sort.add(dir, prop);
        }

        return sort;
    }
}
